package com.xyq.fs.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MyHighLight {
	private static Set<Integer> ss = new HashSet<>();

	public static void sunday(String s, String p) {

		char[] sarray = s.toCharArray();
		char[] parray = p.toCharArray();
		int slen = s.length();
		int plen = p.length();
		int i = 0, j = 0;

		while (i <= slen - plen + j) {
			if (sarray[i] != parray[j]) {
				if (i == slen - plen + j) {
					break;
				}
				int pos = contains(parray, sarray[i + plen - j]);
				if (pos == -1) {
					i = i + plen + 1 - j;
					j = 0;
				} else {
					i = i + plen - pos - j;
					j = 0;
				}
			} else {
				if (j == plen - 1) {
					int start = i - j;
					int end = i;
					for (int ii = start; ii < end + 1; ii++) {
						ss.add(ii);
					}
					i = i - j + 1;
					j = 0;
				} else {
					i++;
					j++;
				}
			}
		}
	}

	public static int contains(char[] str, char ch) {

		for (int i = str.length - 1; i >= 0; i--) {
			if (str[i] == ch) {
				return i;
			}
		}
		return -1;
	}

	public static String high(String str, String[] searchKeys, String qStr, String hStr) {


		str = str.replaceAll("\n+", "<br/>");
		String loStr = str.toLowerCase();
		for (String key : searchKeys) {
			sunday(loStr, key);
		}
		if (ss.size() == 0)
			return str;
		List<Integer> list = new ArrayList<>();
		list.addAll(ss);
		Collections.sort(list);
		StringBuilder sb = new StringBuilder(str);
		int start = -1;
		int groupNum = 0;
		// 标红
		int pre = 0;
		int le = (qStr + hStr).length();
		for (int i = 0; i < list.size(); i++) {
			int nowNum = list.get(i);
			// 上一个号码+1不等于当前号码，表示换了一组
			if (pre + 1 != nowNum && i != 0) {
				if (groupNum == 0) {
					sb.insert(pre + qStr.length() + 1, hStr);
				} else {
					sb.insert(pre + (groupNum + 1) * le - hStr.length() + 1, hStr);
				}
				groupNum++;
				start = nowNum;
				sb.insert(start + groupNum * le, qStr);

			} else if (start == -1) {
				start = nowNum;
				sb.insert(start, qStr);
			}
			pre = nowNum;
		}
		sb.insert(pre + (groupNum + 1) * le - hStr.length() + 1, hStr);
		ss.clear();

		str = null;
		searchKeys = null;
		qStr = null;
		hStr = null;
		loStr = null;
		return sb.toString();
	}

	public static void main(String[] args) {

		// String str = "<span style=\"color:red\"></span>";

		String str = "大法师的福娃地方阿斯蒂芬服务费阿道夫";

		high(str, new String[] { "福娃", "斯蒂", "费阿" }, "<", ">");

	}
}
